package com.hxy.network.core.netty.client;

import cn.hutool.core.util.HexUtil;
import com.hxy.network.core.netty.server.ServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 * @description: netty 客户端启动
 * @program: component_code_integration
 * @author: HCY
 * @create: 2022/12/07 14:22
 */
@Component
@Slf4j
public class NettyClient{
    private  EventLoopGroup group;
    private ChannelFuture mChannelFuture = null;

    /**
     * 客户端监听的端口
     */
    @Value("${netty.clientPort}")
    private int port ;

    @Value("${netty.clientIp}")
    private  String ip;

    @Resource
    private ClientHandler clientHandler;


    /**
     * 客户端启动，并连上服务器端
     */
//    @PostConstruct
    public void init() {
        this.startClient(ip, port);
    }


    public void startClient(String host, int port) {
        try {
            group = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("decoder", new StringDecoder());
                            p.addLast("encoder", new StringEncoder());
                            p.addLast(clientHandler);
                        }
                    });
            // 异步连接
            mChannelFuture = b.connect(host, port).addListener(new ChannelFutureListener() {
                // 监听服务启动状态
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        future.channel().eventLoop().schedule(() -> {
                            log.error("重连netty服务端...");
                            try {
                                startClient(ip,port);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }, 3000, TimeUnit.MILLISECONDS);
                        return;
                    }
                    log.info(String.format("netty客户端启动成功，并监听端口：%s ", port));
                }
            });
            // 同步
            // mChannelFuture = b.connect(host, port).sync();
            // mChannelFuture.isSuccess();
        } catch (Exception e) {
            log.error("启动 netty 客户端出现异常",e);
        }
    }


    /**
     * 客户端通过 Channel 对象向服务器端发送数据
     * @param data 文本数据
     */
    public boolean send(String data) {
        try {
            if (mChannelFuture != null && mChannelFuture.isSuccess()) {
                // 需要给设备发送的 16进制数据
//                String msg = HexUtil.encodeHexStr(data);
//                // 转码
//                ByteBuf message = Unpooled.copiedBuffer(msg.getBytes());
                mChannelFuture.channel().writeAndFlush(data);
                return true;
            }
            return false;
        } catch (Exception e) {
           log.error(this.getClass().getName().concat(".send has error"), e);
            return false;
        }
    }



    @PreDestroy
    public void destroy() {
        group.shutdownGracefully();
    }


}
